﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace OneOfAll.Common.Util
{
    public static class CloneHelper<Tin, TOut>
    {
        private static readonly Func<Tin, TOut> cache = GetFunc();

        private static Func<Tin, TOut> GetFunc()
        {
            ParameterExpression parameterExpression = Expression.Parameter(typeof(Tin), "p");
            List<MemberBinding> memberBindingList = new List<MemberBinding>();
            foreach (var item in typeof(TOut).GetProperties())
            {
                if (!item.CanWrite) continue;
                MemberExpression property = Expression.Property(parameterExpression, typeof(Tin).GetProperty(item.Name));
                MemberBinding memberBinding = Expression.Bind(item, property);
                memberBindingList.Add(memberBinding);
            }
            MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
            Expression<Func<Tin, TOut>> lambda = Expression.Lambda<Func<Tin, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression });
            return lambda.Compile();
        }

        public static TOut CloneByExpression(Tin tin)
        {
            return cache(tin);
        }

        public static TOut CloneByJson(Tin tin)
        {
            string jsonString = JsonConvert.SerializeObject(tin);
            return JsonConvert.DeserializeObject<TOut>(jsonString);
        }
    }
}
